//
//  FeedBackVC.m
//  ProjectforHDX
//
//  Created by Jaesun on 16/7/5.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "FeedBackVC.h"

#import "FeedBackView.h"
#import "MWPhotoBrowser.h"

@interface FeedBackVC ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate, UIActionSheetDelegate,MWPhotoBrowserDelegate>{
    /**
     *  意见反馈图片
     */
    NSMutableArray *photos;
    /**
     *  图片路径
     */
    NSString *filePath;
}

/**
 *  提交数据
 */
@property(nonatomic,strong) NSMutableDictionary *postDict;
/**
 *  意见反馈视图
 */
@property (nonatomic, strong) FeedBackView *feedBackView;

@end

@implementation FeedBackVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupDatas];
    
    [self setupViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

#pragma mark 数据初始化
- (void)setupDatas {
    
}

#pragma mark 视图初始化
- (void)setupViews {
    
    self.navColor = SYSTEM_COLOR;
    
    self.labnav.text= [UtilCheck language:@"setting.feedBack"];
    [self.labnav setFont:NavFontSize];
    [self.labnav setTextColor:[UIColor whiteColor]];
    self.labnav.backgroundColor = [UIColor clearColor];
    
    // view
    self.mBackColor =[UIColor groupTableViewBackgroundColor];
    
    self.feedBackView = [[FeedBackView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 550)];
    
    UITableView *tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    tabelView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    tabelView.tableHeaderView = ({
        UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tabelView.frame.size.width, 550+64)];
        [header addSubview:self.feedBackView];
        header;
    });
    
    // 图片选择
    self.feedBackView.imageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pickImageAction:)];
    
    [ self.feedBackView.imageView addGestureRecognizer:gesture];
    
    // 提交按钮
    [self.feedBackView.submitBtn addTarget:self action:@selector(touchSubmitBtn:) forControlEvents:(UIControlEventTouchUpInside)
     ];
    
    [self.view addSubview:tabelView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



#pragma mark- imagePickControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    image = [Toolobject fixOrientation:image];
    
    NSData * imageDate=UIImageJPEGRepresentation(image, 0.85);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //判断MyImageFolder文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:UPLOAD(@"")];
    if(!fileExists)
    {
        [fileManager createDirectoryAtPath:UPLOAD(@"") withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    filePath=[NSString stringWithFormat:@"%@/DT_%@.jpg",UPLOAD(@""),[UtilCheck DateToTimestamp]];
    
    [imageDate writeToFile:filePath atomically:NO]; //写入文件
        
    photos = [NSMutableArray array];
    
    MWPhoto *photo=[MWPhoto photoWithImage:image];
    [photos addObject:photo];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    self.feedBackView.imageView.image = image;
    
}



#pragma mark - MWPhotoBrowser协议
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    
    return  photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    
    if (index <  photos.count) {
        
        return [photos objectAtIndex:index];
    }
    return nil;
}


#pragma mark- 其他事件
#pragma mark-

#pragma mark 提交
- (void)touchSubmitBtn:(UIButton *)sender {
    
    [self.feedBackView.textView resignFirstResponder];
    self.postDict=[[NSMutableDictionary alloc] initWithCapacity:0];
   
    NSString *txtContent=[UtilCheck clearSpace:self.feedBackView.textView.text isends:YES];
    NSString *titleContent=[UtilCheck clearSpace:self.feedBackView.titleView.text isends:YES];
    
    NSString *typeContent=[UtilCheck clearSpace:self.feedBackView.feedbackTypeLable.text isends:YES];
    NSString *priorityContent=[UtilCheck clearSpace:self.feedBackView.priorityLable.text isends:YES];


    NSInteger limitLength = 10;
    if( txtContent.length < limitLength){
        
        [[BDHUD sharedManager] showWords:[NSString stringWithFormat:[UtilCheck language:@"setting.limitDescrip"],limitLength]];
        
        return;
    }
    else{
        [self.postDict setValue:txtContent forKey:@"problem"];
        [self.postDict setValue:titleContent forKey:@"title"];
        [self.postDict setValue:typeContent forKey:@"back_type"];
        if ([priorityContent isEqualToString:@"紧急"]) {
            [self.postDict setValue:@"1" forKey:@"priority"];
        }else {
            [self.postDict setValue:@"2" forKey:@"priority"];
        }

    }
    if(!filePath) {
        [[BDHUD sharedManager] showWords:[UtilCheck language:@"setting.emptyPhoto"]];
        filePath = @"";
    }
    [self submitFeedback];
}

- (void)submitFeedback {
    
    [[BDHUD sharedManager] showBDUploadHUD:self.view title:nil];
    
    NSLog(@"图片和描述%@",self.postDict);
    
    if (filePath.length != 0) {
        
        //上传图片
        [AFHttpTool postFilewithUrl:@"feedback" parameters:[self.postDict mutableCopy] file:[@[filePath] mutableCopy] success:^(id responseObject) {
            
            
            [[BDHUD sharedManager] dismissHUD];
            
            if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]) {
                NSString *info = [[responseObject objectForKey:@"head"] objectForKey:@"info"];
                
                if([UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]) {
                    info = [UtilCheck  language:@"setting.submitSuccess"];
                }
                [[BDHUD sharedManager] showWords:info];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else {
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
                else{
                    [[BDHUD sharedManager] showWords:[UtilCheck language:@"HUD.nothing"]];
                }
            }
        } progress:^(NSProgress *uploadProgress) {
            
            NSLog(@"%@",uploadProgress);
            
            [[BDHUD sharedManager] setBDUploadProgressHUD:(CGFloat)uploadProgress.fractionCompleted];
            
        } fail:^(id responseObject, NSError *error) {
            
            [[BDHUD sharedManager] dismissHUD];
            NSDictionary *temp=error.userInfo;
            [[BDHUD sharedManager] showWords:[temp objectForKey:@"NSLocalizedDescription"]];
        }];

    }else {

        [AFHttpTool postJsonDatawithUrl:@"feedback"  parameters:self.postDict success:^(id responseObject) {
            
            [[BDHUD sharedManager] dismissHUD];
            
            if(1 == [[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]) {
                
                NSString *info = [[responseObject objectForKey:@"head"] objectForKey:@"info"];
                
                if ([UtilCheck DataIsNuLL:info]) {
                    
                    info = [UtilCheck language:@"setting.cogeAdd"];
                }
                [[BDHUD sharedManager] showWords:info];
                [self.navigationController popViewControllerAnimated:YES];
                
            }
            else {
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
            }
            
        } fail:^(id responseObject, NSError *error) {
            
            [[BDHUD sharedManager] dismissHUD];
            
            if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
            }else {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
            }
            
        }];
        
    }
}


#pragma mark 点击图片
- (void)pickImageAction:(UIGestureRecognizer *)sender
{
    [self.feedBackView.textView resignFirstResponder];
    
    
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:[UtilCheck language:@"setting.feedbackPhoto"] message:@"" preferredStyle:UIAlertControllerStyleAlert]  ;
    
    UIAlertAction *actionAlbum = [UIAlertAction actionWithTitle:[UtilCheck language:@"title.photoAlbum"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            
            UIImagePickerController *Imagepicker = [[UIImagePickerController alloc] init];
            Imagepicker.delegate =self;
            Imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:Imagepicker animated:YES completion:nil];
            
        }
        else{
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"title.noAlbum"]];
        }
        
    }];
    [alertController addAction:actionAlbum];
    
    UIAlertAction *actionCamera = [UIAlertAction actionWithTitle:[UtilCheck language:@"title.takePhotos"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            
            UIImagePickerController *picker =[[UIImagePickerController alloc] init];
            picker.delegate =self;
            //            picker.allowsEditing = YES;
            
            picker.sourceType =  UIImagePickerControllerSourceTypeCamera;
            
            [self presentViewController:picker animated:YES
                             completion:^{
                                 
                             }];
            
            
        }
        else{
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"title.noCamera"]];
        }
        
    }];
    [alertController addAction:actionCamera];
    
    if(photos.count>0){
        UIAlertAction *actionLook = [UIAlertAction actionWithTitle:[UtilCheck language:@"title.largerImage"] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
            
            browser.displayActionButton = NO;//分享按钮,默认是
            browser.displayNavArrows = NO;//左右分页切换,默认否
            browser.displaySelectionButtons = NO;//是否显示选择按钮在图片上,默认否
            browser.alwaysShowControls = NO;//底部 顶部控制条件控件 是否显示,默认否
            browser.zoomPhotosToFill = YES;//是否全屏,默认是
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
            browser.wantsFullScreenLayout = YES;//是否全屏
#endif
            browser.enableGrid =  NO;//是否允许用网格查看所有图片,默认是
            browser.startOnGrid = YES;//是否第一张,默认否
            browser.enableSwipeToDismiss = YES;
            
            
            [browser setCurrentPhotoIndex:0];
            
            
            CustomNavigationController *navCon = [[CustomNavigationController alloc] initWithRootViewController:browser];
            
            [self presentViewController:navCon animated:YES completion:nil];
            
        }];
        [alertController addAction:actionLook];
        UIAlertAction *actionDelete = [UIAlertAction actionWithTitle:[UtilCheck language:@"title.delete"] style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            [UtilCheck DeleLocationimage:filePath];
            filePath=nil;
            self.feedBackView.imageView.image =BDFILEIMAGENAEM(@"default/add_image");
            
        }];
        [alertController addAction:actionDelete];
    }
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:[UtilCheck language:@"title.cancel"] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:action1];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

@end
